import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import * as fs from 'fs';
import * as path from 'path';

@Injectable()
export class UploadService {
    private readonly logger = new Logger(UploadService.name);
    private readonly uploadDir = 'uploads';

    constructor(private configService: ConfigService) {
        // 确保上传目录存在
        if (!fs.existsSync(this.uploadDir)) {
            fs.mkdirSync(this.uploadDir, { recursive: true });
        }
    }

    async saveFile(file: Express.Multer.File) {
        try {
            const filename = file.filename;
            const baseUrl = this.configService.get<string>('BASE_URL') || 'http://localhost:3000';
            const url = `${baseUrl}/uploads/${filename}`;

            return {
                filename,
                url,
                path: file.path
            };
        } catch (error) {
            this.logger.error('Failed to save file:', error);
            throw error;
        }
    }
} 